package com.example.diary;

import static com.example.diary.DatabaseHelper.DB_NAME;
import static com.example.diary.DatabaseHelper.VERSION;
import static com.example.diary.MainActivity.dbHelper;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.preference.PreferenceManager;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author zengzl 用户登录界面
 */
public class Diary extends AppCompatActivity {

    private SharedPreferences pref;//定义一个SharedPreferences对象
    private SharedPreferences.Editor editor;//调用SharedPreferences对象的edit()方法来获取一个SharedPreferences.Editor对象，用以添加要保存的数据
    private Button LOGIN;//登录按钮
    private Button REGISTER;
    private EditText ADMIN_EDIT;//用户名输入框
    private EditText PASSWORD_EDIT;//密码输入框
    private CheckBox SAVE_PASSWORD;//是否保存密码复选框
    private CheckBox SHOW_PASSWORD;//显示或隐藏密码复选框
    private int count = 0; //设计计数器

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 隐藏状态栏 调试通过，写入ppt
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_login);
        // 隐藏actionBar
        getSupportActionBar().hide();
//        icon图标引用
        Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        TextView user = (TextView) findViewById(R.id.user_icon_img);
        TextView passwd = (TextView) findViewById(R.id.password_icon);
        user.setTypeface(iconfont);
        passwd.setTypeface(iconfont);


        //todo Release Note界面 有问题，先注释
//        System.out.println("打印release note");
//        if (getIntent().getBooleanExtra("showReleaseNote", false)) {
//            ReleaseNoteDialogFragment releaseNoteDialogFragment = new ReleaseNoteDialogFragment();
//            releaseNoteDialogFragment.show(getSupportFragmentManager(), "releaseNoteDialogFragment");
//        }

        //获取各组件或对象的实例
        pref = PreferenceManager.getDefaultSharedPreferences(this);
        LOGIN = findViewById(R.id.login_button);
        REGISTER = findViewById(R.id.register_button);
        ADMIN_EDIT = findViewById(R.id.admin);
        PASSWORD_EDIT = findViewById(R.id.password);
        SAVE_PASSWORD = findViewById(R.id.save_password);
        SHOW_PASSWORD = findViewById(R.id.show_password);
        //获取当前“是否保存密码”的状态
        final boolean isSave = pref.getBoolean("save_password", false);
        //当“是否保存密码”勾选时，从SharedPreferences对象中读出保存的内容，并显示出来
        if (isSave) {
            String account = pref.getString("account", "");
            String password = pref.getString("password", "");
            ADMIN_EDIT.setText(account);
            PASSWORD_EDIT.setText(password);
            //把光标移到文本末尾处
            ADMIN_EDIT.setSelection(ADMIN_EDIT.getText().length());
            PASSWORD_EDIT.setSelection(PASSWORD_EDIT.getText().length());
            SAVE_PASSWORD.setChecked(true);
        }
        //用户点击注册时的处理事件
        REGISTER.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(Diary.this, RegActivity.class);
                startActivity(intent);
            }
        });
        //用户点击登录时的处理事件
        LOGIN.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //读出用户名和密码并判断是否正确
                String account = ADMIN_EDIT.getText().toString();
                String password = PASSWORD_EDIT.getText().toString();
                //用户名和密码正确
                if (login_check(account,password)) {
                    editor = pref.edit();
                    //“是否保存密码”勾选
                    if (SAVE_PASSWORD.isChecked()) {
                        editor.putBoolean("save_password", true);
                        editor.putString("account", account);
                        editor.putString("password", password);
                    } else {
                        editor.clear();
                    }
                    //提交完成数据存储
                    editor.apply();
                    //显示登录成功并跳转到主界面活动
                    Intent intent = new Intent(Diary.this, MainActivity.class);
                    intent.putExtra("id_name",ADMIN_EDIT.getText().toString());
                    startActivity(intent);

                    //结束当前活动
                    finish();
                }
                //用户名或密码错误
                else {
                    Toast.makeText(Diary.this, "登录失败,请重新输入！", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //用户点击'显示密码'复选框
        SHOW_PASSWORD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SHOW_PASSWORD.isChecked()) {
                    showOrHide(PASSWORD_EDIT, true);
                } else {
                    showOrHide(PASSWORD_EDIT, false);
                }
            }
        });

    }

    //验证登录
    public boolean login_check(String username,String password) {
        dbHelper = new DatabaseHelper(Diary.this, DB_NAME, null, VERSION);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String sql = "select * from User where name = ? and password = ?";
        Cursor cursor = db.rawQuery(sql, new String[] {username, password});
        if (cursor.moveToFirst()) {
            cursor.close();
            return true;
        }
        return false;
    }

    //当用户离开活动时，检测是否勾选记住密码，若勾选则保存用户输入的用户名及密码
    @Override
    protected void onDestroy() {
        super.onDestroy();
        editor = pref.edit();
        String account = ADMIN_EDIT.getText().toString();
        String password = PASSWORD_EDIT.getText().toString();
        if (SAVE_PASSWORD.isChecked()) {
            editor.putBoolean("save_password", true);
            editor.putString("account", account);
            editor.putString("password", password);
        } else {
            editor.clear();
        }
        editor.apply();
    }

    //显示或隐藏密码
    private void showOrHide(EditText PASSWORD_EDIT, boolean isShow) {

        //记住光标开始的位置
        int pos = PASSWORD_EDIT.getSelectionStart();
        if (isShow) {
            PASSWORD_EDIT.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            PASSWORD_EDIT.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
        PASSWORD_EDIT.setSelection(pos);
    }

}